package com.mt.config;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONUtil;
import com.mt.RedisUtils;
import com.mt.pojo.Film;
import com.mt.service.FilmService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.mt.constants.SYS.TOP_FILM_CACHE;

/**
 * @author Wang
 * @Description 本地缓存启动
 * @date 2020/11/25-20:07
 */
@Component
@Slf4j
public class FilmCacheInitialization implements ApplicationRunner {

    @Autowired
    FilmService filmService;
    @Autowired
    RedisUtils redisUtils;

    @Override
    public void run(ApplicationArguments args)throws Exception{
        //启动时调用,之后定时刷新
        log.info("init初始化中,开始缓存电影信息");
        refreshFilmCache();
        //定时启动线程更新缓存,refresh
    }
    private void refreshFilmCache() {
        try {
            for (int i = 0; i < 3; i++) {
                List<Film> cacheFilms = filmService.getTopFilm();
                JSONConfig jsonConfig = JSONConfig.create()
                        .setDateFormat("yyyy-MM-dd")
                        .setIgnoreNullValue(false);
                JSON s = JSONUtil.parse(cacheFilms,jsonConfig);
                redisUtils.set(TOP_FILM_CACHE,
                        s.toStringPretty(),6L, TimeUnit.HOURS);
                FilmCacheManager.getInstance().put(TOP_FILM_CACHE, cacheFilms);
                if (!cacheFilms.isEmpty()) {
                    log.info("缓存电影信息成功 !!");
                    break;
                }else {
                    log.error("重新进行缓存");
                }
            }
        } catch (Exception e) {
            log.error("启动缓存失败:" + e.toString());
        }
    }
}
